/*
 * @Author: 糊涂的老知青
 * @Date: 2022-05-17
 * @Version: 1.0.0
 * @Description:
 */
package infra_domainservice

import (
	"fmt"
	"lzq-admin/base/domainservice"
	"lzq-admin/config"
	infra_model "lzq-admin/internal/infrastructure/model"
	token "lzq-admin/pkg/auth"
	"lzq-admin/pkg/hsflogger"
	"lzq-admin/pkg/httpclient"
	"lzq-admin/pkg/orm"
	"lzq-admin/pkg/tenant"
	"lzq-admin/pkg/utility"

	"github.com/gin-gonic/gin"
)

type LogAuditLogActionService struct {
	domainservice.BaseDomainService
}

func NewDSLogAuditLogAction(c *gin.Context) *LogAuditLogActionService {
	return &LogAuditLogActionService{
		domainservice.BaseDomainService{
			GinCtx: c,
		},
	}
}

func (s *LogAuditLogActionService) Insert(inputDto infra_model.CreateLogAuditLogActionDto) error {
	var result infra_model.LogAuditLogAction
	result.ID = utility.UuidCreate()
	claims := token.GetClaims(s.GinCtx)
	if len(claims.Id) > 0 {
		result.UserID = claims.Id
		result.UserName = claims.Name
		result.LoginName = claims.LoginName
		if config.Config.UseMultiTenancy {
			tenantInfo, _ := tenant.GetTenantById(claims.TenantId)
			result.TenantName = tenantInfo.Name
		}
	}
	result.ServiceModuleCode = config.Config.ServerConfig.ServiceModuleCode
	result.LogAuditLogActionBase = inputDto.LogAuditLogActionBase
	if ipInfo, err := httpclient.GetIpArea(result.LogAuditLogActionBase.ClientIPAddress); err != nil {
		hsflogger.LogError("获取Ip区域信息失败", err)
	} else {
		result.LogAuditLogActionBase.ClientIPArea = fmt.Sprintf("%s %s %s %s", ipInfo.Country, ipInfo.Prov, ipInfo.City, ipInfo.Lsp)
	}

	if _, err := orm.NewLzqOrm(s.GinCtx).ISession().Insert(&result); err != nil {
		return err
	}
	return nil
}

func (s *LogAuditLogActionService) AnonymousInsert(inputDto infra_model.LogAuditLogAction) error {
	inputDto.ID = utility.UuidCreate()
	inputDto.ServiceModuleCode = config.Config.ServerConfig.ServiceModuleCode
	if ipInfo, err := httpclient.GetIpArea(inputDto.LogAuditLogActionBase.ClientIPAddress); err != nil {
		hsflogger.LogError("获取Ip区域信息失败", err)
	} else {
		inputDto.LogAuditLogActionBase.ClientIPArea = fmt.Sprintf("%s %s %s %s", ipInfo.Country, ipInfo.Prov, ipInfo.City, ipInfo.Lsp)
	}
	if _, err := orm.NewLzqOrm(s.GinCtx).ISession().Insert(&inputDto); err != nil {
		return err
	}
	return nil
}
